import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { MyTableConfig, SortFile } from '@app/shared/components/ant-table/ant-table.component';
import { MantenanceService, Maintenance } from '@app/core/services/http/maintenance/mantenance.service';
import { PageHeaderType } from '@app/shared/components/page-header/page-header.component';
import { WeekDay, monthly, monthday, MinuteSecondList, Hours } from '@app/shared/models/dateTime.models';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
@Component({
  selector: 'app-mantenance',
  templateUrl: './mantenance.component.html',
  styleUrls: ['./mantenance.component.less']
})
export class MantenanceComponent implements OnInit {
  formdata!: FormGroup;
  tableConfig!: MyTableConfig;
  dataList: [] = [];
  isCollapse: boolean = false;
  selectWeek = new Set();
  selectMonth = new Set();
  selectMonthDay = new Set();
  weekDayList = WeekDay;
  monthlyList = monthly;
  monthdayList = monthday();
  hoursList = Hours();
  minuteSecondList = MinuteSecondList();
  showEditForm: boolean = false;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '查询表格（表头可拖动，点击列表的"查看"按钮，演示在当前tab打开详情操作，如果需要新开tab展示详情，请跳转到"功能>页签操作"中查看演示效果）',
    // desc: '表单页用于向用户收集或验证信息，基础表单常见于数据项较少的表单场景。',
    breadcrumb: ['首页', '列表页', '查询表格']
  };
  @ViewChild('operationTpl', { static: true }) operationTpl!: TemplateRef<any>;
  checkedCashArray: NzSafeAny[] = [];
  constructor(private fb: FormBuilder) {}
  cronDetailFormGroup!: FormGroup;
  ngOnInit(): void {
    this.initTable();
  }
  formInit(param: Partial<Maintenance>): void {
    this.formdata = this.fb.group({
      name: [param.name, [Validators.required]],
      comment: [param.comment, [Validators.required]],
      cronStartTime: [param.cronStartTime, [Validators.required]],
      cronStopTime: [param.cronStopTime, [Validators.required]],
      cronTime: [param.cronTime],
      cronDetail: this.fb.group({
        cronHours: [param.cronDetail?.cronHours],
        cronMinutes: [param.cronDetail?.cronHours],
        cronMonth: [param.cronDetail?.cronMonth],
        cronDays: [param.cronDetail?.cronDays],
        cronMonthDay: [param.cronDetail?.cronMonthDay],
        cronWeek: [param.cronDetail?.cronWeek]
      }),
      afterTime: [param.afterTime, [Validators.required]],
      loopTimes: [param.loopTimes, [Validators.required]],
      perunit: [param.loopTimes, [Validators.required]]
    });
  }
  getDataList(e?: NzTableQueryParams): void {
    this.dataList = [];
  }

  submitForm(): void {
    this.buildCornTime();
    console.log('this.formdata.value() ', this.formdata.value);
  }
  caneal(): void {
    this.showEditForm = false;
  }

  // */1 * * * *
  // # 文件格式說明
  // # ┌──分鐘（0 - 59）
  // # │  ┌──小時（0 - 23）
  // # │  │  ┌──日（1 - 31）
  // # │  │  │  ┌─月（1 - 12）
  // # │  │  │  │  ┌─星期（0 - 6，表示从周日到周六）
  // # │  │  │  │  │
  // # *  *  *  *  * 被執行的命令
  private buildCornTime(): void {
    const cronType = this.formdata.get('perunit')?.value;
    this.cronDetailFormGroup = this.formdata.get('cronDetail') as FormGroup;
    const cronHours = this.cronDetailFormGroup.get('cronHours')?.value;
    const cronMinutes = this.cronDetailFormGroup.get('cronMinutes')?.value;
    const cronDays = this.cronDetailFormGroup.get('cronDays')?.value;
    const cronWeek = this.selectWeek.size > 0 ? Array.from(this.selectWeek.values()).join(',') : '*';
    const cronMonthDay = this.selectMonthDay.size ? Array.from(this.selectMonthDay.values()).join(',') : '*';
    const cronMonth = this.selectMonth.size ? Array.from(this.selectMonth.values()).join(',') : '*';
    console.log('this.selectMonthDay ', this.selectMonthDay)
    let patchvalue = {};
    let crontime = '';
    const m = cronMinutes.length > 0 ? cronMinutes.join(',') : '*';
    const h = cronHours.length > 0 ? cronHours.join(',') : '*';
    if (cronType === 'week') {
      crontime = `${m} ${h} * * ${cronWeek}`;
      patchvalue = {
        cronMinutes: cronMinutes,
        cronHours: cronHours,
        cronWeek: Array.from(this.selectWeek.values())
      };
    } else if (cronType === 'day') {
      crontime = `${m} ${h} */${cronDays} * *`;
      patchvalue = {
        cronMinutes: cronMinutes,
        cronHours: cronHours,
        cronDays: cronDays
      };
    } else if (cronType === 'month') {
      crontime = `${m} ${h} ${cronMonthDay} * *`;
      patchvalue = {
        cronMinutes: cronMinutes,
        cronHours: cronHours,
        cronMonthDay: Array.from(this.selectMonthDay.values())
      };
    } else {
      patchvalue = {
        cronMinutes: cronMinutes,
        cronHours: cronHours,
        cronMonth: Array.from(this.selectMonth.values())
      };
      crontime = `${m} ${h} ${cronMonthDay} ${cronMonth} *`;
    }
    console.log('crontime', crontime);
    // patch value
    this.formdata.get('cronDetail')?.patchValue(patchvalue);
  }

  toggleCollapse(): void {}

  add(): void {
    this.showEditForm = true;
  }

  resetForm(): void {}
  reloadTable(): void {}
  selectedChecked(e: any): void {}
  changePageSize(evnet: number): void {}

  del(id: number): void {}
  edit(id: number): void {
    this.formInit({
      name: '',
      comment: '',
      cronStartTime: '',
      cronStopTime: '',
      cronTime: '',
      cronDetail: {
        cronHours: [1,2],
        cronMinutes: [2,4],
        cronMonth: [],
        cronDays: 2,
        cronMonthDay: [],
        cronWeek: []
      },
      afterTime: '',
      loopTimes: 2,
      perunit: ''
    });
  }

  private initTable(): void {
    this.tableConfig = {
      showCheckbox: true,
      headers: [
        {
          title: '名称',
          field: 'name',
          width: 100
        },
        {
          title: '内部备注',
          width: 100,
          field: 'available'
        },
        {
          title: '外部备注',
          width: 70,
          field: 'sex',
          pipe: 'sex'
        },
        {
          title: '有效性',
          width: 100,
          field: 'mobile'
        },
        {
          title: '创建人',
          width: 100,
          field: 'email'
        },
        {
          title: '最后登录时间',
          width: 120,
          field: 'lastLoginTime',
          pipe: 'date:yyyy-MM-dd HH:mm'
        },
        {
          title: '创建时间',
          width: 100,
          field: 'createTime',
          pipe: 'date:yyyy-MM-dd HH:mm'
        },
        {
          title: '电话',
          width: 100,
          field: 'telephone'
        },
        {
          title: '',
          width: 100,
          field: 'departmentName'
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 150,
          fixed: true
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1
    };
  }
}
